import json
import os.path
import sys
from os.path import dirname, abspath

# path = os.path.dirname(__file__) + '\config.json'
import global_config

path = global_config.JSON_CONFIG_PATH


# path = r"D:/NinePrice/config.json"


def init_conf(p: str) -> None:
    content = '"email":"","password:""'
    # with open(p, 'w', encoding="UTF-8") as f:
    #     json.dump(json.loads(content), f, ensure_ascii=False)
    # f.close()
    f = open(p, 'w', encoding='UTF-8')
    f.write(content)
    f.close()


def get(key=None):
    try:
        with open(path, encoding="UTF-8") as j:
            r = json.load(j)

        if key is None:
            return r
        else:
            return r[key]
    finally:
        j.close()


def update(key, value):
    print("设置配置文件")
    content = get()
    content[key] = value
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True


def append_list(key, value) -> bool:
    print("追加配置文件")
    content = get()
    li = list(content[key])
    li.append(value)  # 追加
    content[key] = li
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True


def delete_list(key, index: int) -> bool:
    print("删除列表配置文件")
    content = get()
    li = list(content[key])
    del li[index]  # 移除
    content[key] = li
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True


def update_list(key, index: int, value) -> bool:
    print("修改列表配置文件")
    content = get()
    li = list(content[key])
    li[index] = value  # 修改
    content[key] = li
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True


def delete(key: str) -> bool:
    print("删除配置文件")
    content = get()
    for item in content:
        del item[key]
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True


def add(key: str, value: any) -> bool:
    print("添加配置文件")
    content = get()
    content[key] = value
    with open(path, 'w', encoding="UTF-8") as f:
        json.dump(content, f, ensure_ascii=False)
    f.close()
    return True
